package com.weatherquery.utils;

import java.sql.*;

/**
 * @Author Natural-Pride
 * @Date 2023/12/17 10:35
 * @注释
 */
public class dbHelper {
    private static final String DRIVER = "com.mysql.cj.jdbc.Driver";
    private static final String URL = "jdbc:mysql://47.109.58.164:3306/weather_city?characterEncoding=utf8";
    private static final String USERNAME = "weather_city";
    private static final String PASSWORD = "123456";

    // 静态初始化注册驱动
    static {
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    // 获取连接
    public static Connection getConnection() throws SQLException {
        Connection connection = null;
        // 通过DriverManager连接数据库，传入数据库URL、用户名和密码
        connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);

        return connection;  // 返回连接对象
    }


    /**
     * 关闭结果集、语句和连接
     * @param resultSet 结果集对象
     * @param statement 语句对象
     * @param connection 连接对象
     */
    public static void close(ResultSet resultSet, Statement statement, Connection connection) {
        try {
            if (resultSet != null && !resultSet.isClosed()) {
                resultSet.close();
            }
            if (statement != null && !statement.isClosed()) {
                statement.close();
            }
            if (connection != null && !connection.isClosed()) {
                connection.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

}
